package com.dailyblue.java.servlet.controller;

import com.dailyblue.java.jdbc.pack0325.bean.Emp;
import com.dailyblue.java.jdbc.pack0325.dao.EmpDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/emp")
public class EmpController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 页面想要获取数据
        // 1. 产生DAO类的对象
        EmpDAO edao = new EmpDAO();
        // 2. 调用DAO类的查询方法获取到集合
        List<Emp> list = edao.findAllEmp();
        // 3. 保存list集合到容器(page、request、session和application)
        HttpSession session = request.getSession();
        session.setAttribute("EMP", list);
        // 4. 跳转到页面
        response.sendRedirect("index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 处理请求的乱码
        request.setCharacterEncoding("utf-8");
        // 1. 接收请求的参数
        String ename = request.getParameter("ename");
        System.out.println("接收的参数是： " + ename);
        // 2. 产生对象
        EmpDAO edao = new EmpDAO();
        // 3. 调用方法
        List<Emp> list = edao.findEmpByEname(ename);
        // 4. 保存到session容器中
        request.getSession().setAttribute("EMP", list);
        // 5. 跳转
        response.sendRedirect("index.jsp");
    }
}
